//
//  OAuthViewController.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/5/11.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let APP_KEY = "3690508227"
    let APP_SECRET = "e83c26af6ae0c66e36cedb22a9326bf9"
    let REDIRECT_URL = "http://www.sixstr.me"
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Swift微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.close))
        
        //获取未授权的requestToken
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&response_type=code&redirect_uri=\(REDIRECT_URL)"
        let url = NSURL(string: urlStr)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }

    func close() -> () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var webView: UIWebView = UIWebView()

}

extension OAuthViewController: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if !request.URL!.absoluteString.hasPrefix(REDIRECT_URL) {
            return true
        }
        
        if request.URL!.query!.hasPrefix("code=") {
            print("授权成功")
            
            let code = request.URL!.query?.substringFromIndex("code=".endIndex)
            
            print(request.URL!.absoluteString)
            
            print(code)
            
            //利用授权的requestToke换取accessToken
            
            loadAccessToken(code!)
            
        } else {
            print("取消授权")
            
            close()
        }
        
        return false
    }
    
    private func loadAccessToken(code: String) {
        let path = "oauth2/access_token"
        
        let params = ["client_id": APP_KEY,
                      "client_secret": APP_SECRET,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": REDIRECT_URL]
        
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) in
            print(JSON)
            
            let account = UserAccount(dict: JSON as! [String: AnyObject])
            
            account.loadUserInfo({ (account) in
                account.saveAccount()
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerKey, object: false)
                }, failure: { (error) in
                    SVProgressHUD.showInfoWithStatus("网络不给力")
                    SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            })
            
            }) { (_, error) in
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
                SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("Loading")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
